package com.clp.protocol.iec104.iec104.apdu.asdu.infoobj.infoelem;

import com.clp.protocol.core.nbytepdu.BaseNBytePduClip;
import com.clp.protocol.core.pdu.ByteToStringFormat;
import com.clp.protocol.iec104.iec104.definition.Tm;
import com.clp.protocol.iec104.iec104.definition.TypeTag;
import com.clp.util.ByteUtil;
import io.netty.buffer.ByteBuf;
import lombok.Getter;

import java.util.Objects;
import java.util.function.Consumer;

/**
 * 设定值命令，短浮点数
 */
@Getter
public class C_SE_NC_1_InfoElem extends TaInfoElem {
    /**
     * 短浮点数用float表示
     */
    private float floatVal;

    public C_SE_NC_1_InfoElem() {
        this(-1f);
    }

    public C_SE_NC_1_InfoElem(float floatVal) {
        super(TypeTag.C_SE_NC_1);
        this.floatVal = floatVal;
    }

    @Override
    public InfoElem refreshFrom(ByteBuf buf) {
        byte[] bytes = new byte[typeTag().getInfoElemBytesLen()];
        buf.readBytes(bytes);
        this.floatVal = ByteUtil.bytes4ToFloatLE(bytes);
        return this;
    }

    @Override
    public boolean isValid() {
        return true;
    }

    @Override
    public void writeBytesTo(ByteBuf buf) {
        buf.writeFloatLE(floatVal);
    }

    @Override
    public void writeFormattedByteStringsTo(StringBuilder sb, String frameClipBytesSeparator, String byteSeparator, ByteToStringFormat byteFormat) {
        byte[] bytes = ByteUtil.floatToByte4LE(floatVal);
        sb.append(byteFormat.format(bytes[0]));
        for (int i = 1; i < bytes.length; i++) {
            sb.append(byteSeparator).append(byteFormat.format(bytes[i]));
        }
    }

    @Override
    public void writeSimpleDescriptionTo(StringBuilder sb) {
        sb.append(floatVal);
    }

    @Override
    public void writeDetailDescriptionTo(StringBuilder sb) {
        sb.append("设定值，短浮点数：").append(floatVal);
    }

    @Override
    public Tm.ValType getValType() {
        return Tm.ValType.FLOAT;
    }

    @Override
    public Number getNumberVal() {
        return floatVal;
    }

    @Override
    protected void forEachOneLevelChild(Consumer<BaseNBytePduClip<?>> consumer) {
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        C_SE_NC_1_InfoElem that = (C_SE_NC_1_InfoElem) o;
        return Float.compare(that.floatVal, floatVal) == 0;
    }

    @Override
    public int hashCode() {
        return Objects.hash(floatVal);
    }
}
